/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * 单链表实现队列
 * 尾插 + 头删
 */
@SuppressWarnings({"all"})
public class ListQueue {
    public Node head; // 指向链表的头
    public Node last; // 指向链表的尾

    class Node{
        public int val; // 存储的数据
        public Node next; // 存储下一个节点的地址

        public Node(int val) {
            this.val = val;
        }
    }

    // 入队列
    public void offer(int val){
        addLast(val);
    }

    // 出队列
    public int poll(){
        return removeFirst();
    }

    // 查看队头元素
    public int peek(){
        if (head == null){
            throw new RuntimeException("当前队列为空!");
        }
        return head.val;
    }

    // 头删法
    public int removeFirst(){
        // 判空
        if (head == null){
            throw new RuntimeException("当前队列为空!");
        }
        // 考虑只剩下一个节点
        if (head.next == null){
            int val = head.val;
            head = null;
            last = null;
            return val;
        }
        // 头部删除
        int val = head.val;
        head = head.next;
        return val;
    }

    // 尾插法
    public void addLast(int val){
        Node newNode = new Node(val);
        if (head == null){
            // 链表为空
            head = newNode;
            last = newNode;
            return;
        }
        // 尾插
        last.next = newNode;
        last = last.next;
    }

    // 返回队列的长度
    public int size(){
        int count = 0;
        Node cur = head;
        while (cur != null){
            count++;
            cur = cur.next;
        }
        return count;
    }

}
